#include "taskthreadmanager.h"
// app common
#include <log/logger.h>
#include "taskqueue.h"
#include "taskthread.h"

namespace thread{

TaskThreadManager::TaskThreadManager(
      uint32_t   worker_count,
      std::map<uint32_t, TaskQueue>&  map_task_queue):
      worker_count_(worker_count),
      map_task_queue_(map_task_queue)
{
  MEMBER_DEBUG_LOG("[+]TaskThreadManager::ctor");
  if(worker_count_ < 1)
  {
    worker_count_ = 1;
  }
  MEMBER_DEBUG_LOG("[-]TaskThreadManager::ctor");
}

TaskThreadManager::~TaskThreadManager()
{
  MEMBER_DEBUG_LOG("[+]TaskThreadManager::~TaskThreadManager");
  this->Stop();
  MEMBER_DEBUG_LOG("[+]TaskThreadManager::~TaskThreadManager");
}

bool TaskThreadManager::Init()
{
  MEMBER_DEBUG_LOG("[+]TaskThreadManager::Init");
  for (uint32_t i = 0; i < worker_count_; ++i)
  {
    workers_.push_back(new TaskThread(map_task_queue_[i]));
  }
  //For inheritance, other initialization code goes here

  MEMBER_DEBUG_LOG("[-]TaskThreadManager::Init");
  return true;
}

void TaskThreadManager::Start()
{
  MEMBER_DEBUG_LOG("[+]TaskThreadManager::Start");
  std::list<TaskThread*>::const_iterator lit = workers_.begin();
  std::list<TaskThread*>::const_iterator eit = workers_.end();
  for (; lit != eit; ++lit)
  {
    (*lit)->Start();
  }
  MEMBER_DEBUG_LOG("[-]TaskThreadManager::Start");
}

void TaskThreadManager::Stop()
{
  MEMBER_DEBUG_LOG("[+]TaskThreadManager::Stop");
  std::list<TaskThread*>::const_iterator lit = workers_.begin();
  std::list<TaskThread*>::const_iterator eit = workers_.end();
  for (; lit != eit; ++lit)
  {
    (*lit)->set_stop();
  }
  MEMBER_DEBUG_LOG("[-]TaskThreadManager::Stop");
}

void TaskThreadManager::Term()
{
  MEMBER_DEBUG_LOG("[+]TaskThreadManager::Term")
  std::list<TaskThread*>::iterator it = workers_.begin();
  for(; it != workers_.end(); ++it)
  {
    (*it)->Join();
    delete (*it);
    *it = NULL;
  }
  workers_.clear();
  //For inheritance, other code goes here

  MEMBER_DEBUG_LOG("[-]TaskThreadManager::Term")
}

}

